package com.gly091020.mixin;

import com.gly091020.ChineseChestFun;
import net.minecraft.inventory.Inventory;
import net.minecraft.loot.LootTable;
import net.minecraft.loot.context.LootContextParameterSet;
import net.minecraft.util.math.random.Random;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

import java.util.ArrayList;
import java.util.List;

import static com.gly091020.ChineseChest.config;

@Mixin(LootTable.class)
public abstract class LootableContainerBlockMixin {
    @Inject(method = "supplyInventory", at = @At("RETURN"))
    public void setItem(Inventory inventory, LootContextParameterSet parameters, long seed, CallbackInfo ci){
        if(!config.isEnable){return;}
        float itemMultiple = ChineseChestFun.getItemMultiple(seed);
        int multiple1 = (int)itemMultiple;
        float multiple2 = itemMultiple - multiple1;
        int shouldFillSlotCount = (int)(inventory.size() * multiple2);
        List<Integer> l1 = new ArrayList<>();
        Random random = Random.create(seed);
        for (int i = 0; i < shouldFillSlotCount; i++) {
            int r;
            do {
                r = random.nextBetween(0, shouldFillSlotCount);
            } while (l1.contains(r));
            l1.add(r);
        }
        for(int i = 0; i < inventory.size(); i++){
            var stack = inventory.getStack(i);
            stack.setCount(stack.getCount() * (l1.contains(i) ? multiple1 + 1 : multiple1));
            if(stack.getMaxCount() < stack.getCount()){
                stack.setCount(stack.getMaxCount());
            }
        }
        ChineseChestFun.removeMultiple(seed);
    }
}
